require 'gl'
require 'glu'

include Gl
include Glu

def object_for_shape(shape)
  $game.objects.each do |object|
    if object.is_a? MovableObject then
      if object.shape == shape then
        return object
      end
    end
  end
  return nil
end

def draw_shape (shape)
  v = shape.adjusted_verts
	$game.gl do
		glBegin(GL_LINE_LOOP)
			v.each do |vert|
			  vert = $game.camera.adjusted_vect(vert)
				glVertex2f(vert.x, vert.y)
			end
		glEnd()
	end
end

class DrawableObject
  attr_reader :image
  attr_accessor :x, :y, :angle, :active
  
  def initialize(image)
    @image = image
    $game.objects << self
    @x, @y, @angle = 0.0, 0.0, 0.0
    @zindex = 1
    @active = true
  end
  
  def update
    
  end
  
  def draw
    v = $game.camera.adjusted_coords(@x,@y)
    @image.draw_rot(v.x, v.y, @zindex, @angle)
  end
  
  def draw_hud
    # nothing
  end
  
  
  def draw_debug
    
  end
  
  def destroy
    # we do this redirection to allow the difference between
    # being 'destroyed' and being 'removed' from the game
    remove
  end
  
  def remove
    $game.remove_objects << self
  end
  
    
end

class MovableObject < DrawableObject
  attr_accessor :body, :shape, :type
  attr_reader :static, :collides_with_air, :height
  
  def initialize(image, shape_points, static=false)
    super(image)
    
    @body = CP::Body.new(Float::MAX,Float::MAX)
    
    @shape_points = shape_points
    @shape = CP::Shape::Poly.new(@body, shape_points, CP::Vec2.new(0,0))
    
    @shape.body.p = CP::Vec2.new(0.0, 0.0) # position
    @shape.body.v = CP::Vec2.new(0.0, 0.0) # velocity
    
    if (static)
      $game.space.add_static_shape(@shape)
      @static = true
    else
      $game.space.add_shape(@shape)
      $game.space.add_body(@body)
    end
    
    # ground hits ground, air hits air, no crossover unless this is true
    @collides_with_air = false 
    
    # can be :ground, :air
    @height = :ground 
    
    @type = :generic
    
  end
  
  def recalculate_moment
    @body.i = CP::moment_for_poly(@body.m, @shape_points, CP::Vec2.new(0,0))
  end
  
  def draw
    @x, @y, @angle = @shape.body.p.x, @shape.body.p.y, @shape.body.a.radians_to_gosu
    super
  end
  
  def warp(vect)
    @shape.body.p = vect
    
    $game.space.rehash_static
    
  end
  
  def draw_debug
    draw_shape @shape
  end
  
  def collided_with(other_object)
    return true
  end
  
  def hit_by_weapon(shot, type, damage)
    hurt(damage, shot)
  end
  
  def hurt(damage, shot)
    if @health == nil then
      return 
    end
    
    @health -= damage
    
    if @health <= 0 then
      if shot.owner.respond_to? :destroyed_object then
        shot.owner.destroyed_object self
      end
      destroy
    end
  end
  
  def update
    @body.reset_forces
    super
  end
  
  def explode
    Explosion.new(vect(@body.p.x, @body.p.y))
  end
  
  
  
end
